<style scoped>
.sh-filebody {
    width: 100%;
    height: 100%;
    position: relative;
    overflow-y: auto;
  padding: 60px;
    box-sizing: border-box;
   display: flex;
   flex-wrap: wrap;
  align-content: flex-start
}
.sh-filecontent {
  display: inline-block;
  width: 50px;
  height: 50px;
  border: 0.5px solid #333;
  margin: 15px;
}
.sh-totalfooter {
  position: absolute;
  bottom: 0;
  width: 100%;
  line-height: 50px;
background: #adceea;
text-indent: 50px;
border-top: 0.5px solid #adceea;
letter-spacing: 1px;
word-spacing: 5px;
}
.file-checked {
  background-color: #326591;
  border-radius: 7px;
}
div {
  user-select: none;
}
.sh-dir {
  position: relative;
  width: 99.6%;
  height: calc(100vh - 169px);
  overflow-y: auto;
  background-color: rgba(7, 250, 252,.4);
  border-top:1px solid rgba(7, 250, 252,.8);
}
.uploadwrap{
  background-color: #009688;
   border-radius:6px;
}
.uploadlist{
  padding-inline-start: 0px;
  margin-block-start: 0px;
  margin-block-end: 0px;
  
}
.uploadlist li{
  padding: 5px 12px;
  text-align: center;
  list-style: none;
  border-bottom: 1px solid #adceea;
  color: #e5e5e5;
}
.uploadlist li:hover{
 background-color: #e5e5e5;
  color: #333;
  cursor: pointer;
}
.seldiv {
  position:absolute;
  width:0px;
  height:0px;
  font-size:0px;
  margin:0px;
  padding:0px;
  border:1px dashed #0099FF;
  background-color:#C3D5ED;
  z-index:1000;
  opacity: 0.6;
  pointer-events: none;
}
.lightbgcolor{
  background-color: #326591;
  border-top:1px solid #fff;
  border-right: 1px solid #fff;
  border-radius: 3px;
}
.darkbgcolor{
  background-color: #009688;
}
</style>
<template >
  <div class="sh-dir" :style="'background-color:'+$store.state.zhuti.bgcolor">
    <div class="sh-filebody"  @mouseup=handleup($event) @mousemove.self="handlemove($event)" @mousedown.self="handlemousedown($event)" @contextmenu.self="bodycontextmenu($event)" ref="filebody">
      <template v-for="(item,index) in filelist">
        <paper 
          :key="'file'+index"
          @contextmenu="Handlecontextmenu($event,item,index)"
          :class="{'file-checked':item.checked}"
          @click.native.exact="handleClick(item,index)"
          @click.ctrl.native="handleCtrlClick(item,index)"
          @click.shift.native="handleShiftClick(item,index)"
          @dblclick.native="handelDbclick(item,index)"
          :fileitem="item"
          >
        </paper>
      </template>
      <div ref="selDiv" v-show="showseldiv" class="seldiv"></div>
      <div
        v-show="showcontextmenufolder"
        class="uploadwrap"
        style="border: 0.5px solid #e5e5e5; position: absolute;"
        :style="styls2"
      >
        <slot name="filecontextmenu">
          <ul :class="'uploadlist '+showtableclass">
            <slot name="contextmenufolder"></slot>
            <li @click.self.stop="uploadfile" 
            v-if="filestate===1&&$store.state.userauthoritylist.includes('pw_zlgl_fbgl_upload')"
            >上传文件</li>
            <li @click.self.stop="uploadfiles" v-if="filestate===1&&$store.state.userauthoritylist.includes('pw_zlgl_fbgl_upload')">批量上传文件</li>
            <li @click.self.stop="uploaddir"  v-if="filestate===1&&$store.state.userauthoritylist.includes('pw_zlgl_fbgl_upload')">上传文件夹</li>
            <li @click.self.stop="reload">刷新</li>
          </ul>
        </slot>
      </div>
      <div
        v-show="showcontextmenu"
        style="border: 0.5px solid #e5e5e5; position: absolute;"
        :style="styls"
       class="uploadwrap"
      >
        <slot name="filecontextmenu">
          <ul :class="'uploadlist '+showtableclass">
            <li @click.self.stop="open" v-show="filechecked.length==1&&onefile.type=='folder'">打开</li>
            <li @click.self.stop="yulan" v-show="filechecked.length==1&&onefile.type=='file'">预览</li>
            <li @click.self.stop="download"  v-show="filechecked.length>=1&&$store.state.userauthoritylist.includes('pw_zlgl_fbgl_down')">下载</li>
          <li @click.self.stop="uploadfile" v-show="filechecked.length==1&&onefile.type=='file'&&$store.state.userauthoritylist.includes('pw_zlgl_fbgl_upload')">上传文件</li>
          <li @click.self.stop="deletefile"  v-show="filechecked.length>=1"  v-if="filestate===1&&$store.state.userauthoritylist.includes('pw_zlgl_fbgl_del')">删除</li>
          
          </ul>
        </slot>
      </div>
      <input style="display:none" type="file" ref="uploadfile" id="file" name="file"  @change="filechangeed($event)" />
      <input
        style="display:none"
        type="file"
        ref="uploadfiles"
        name="file"
        id="files"
        multiple
        @change="filechangeed($event)"
      />
      <input
        style="display:none"
        type="file"
        webkitdirectory
        ref="uploaddir"
        name="fileFolder"
        id="dirs"
        @change="filechangeed($event)"
      />
    </div>
   <div class="sh-totalfooter">共{{filelist.length}}个,已选中{{filechecked.length}} &nbsp;<span v-if="fileuptime[0]&&fileuptime[0].fileuptime">上传时间：{{fileuptime[0]?fileuptime[0].fileuptime:''}}</span></div>  
  </div>
</template>
<script>
import paper from "./paper"
export default {
  name: "floder-copy",
  components:{paper},

  props: {
    filelist: {
      type: Array,
      default: () => new Array()
    },
    action: {
      type: String,
      default: ""
    },
    filestate:{
      type:Number
    }
  },
  data() {
    return {
      showcontextmenu: false,
      styls: "",
      showcontextmenufolder: false,
      styls2: "",
      filecate:'',
      pre:0,
      showseldiv:false,
      _x:null,
      _y:null,
      startX:null,
      startY:null,
      selList:[]
    };
  },
  computed: {
    onefile(){
      return this.filechecked[0]
    },
    filechecked() {
      return this.filelist.filter(ele => {
        return !!ele.checked;
      });
    },
    fileuptime(){
      return this.filechecked.filter(item=>{
        if(item.fileuptime){
           return item.fileuptime
        }else{
          return item;
        }
       
      })
    },
      showtableclass(){
      if(this.$store.state.theme==='darktheme'){
        return 'darkbgcolor'
      }else{
        return 'lightbgcolor'
      }
      }
  },
  methods: {
    selectAll(){
      const _this = this;
      this.filelist.forEach((ele,index)=>{
        ele.checked=true;
         _this.$set(_this.filelist, index, ele);
        });
    }
    ,
    submit($event) {
      return false;
    },
    filechangeed($event) {
      this.$emit("filechange", $event);
      // console.log($event);
    },
    open() {
      // console.log("打开", this.filechecked);
      this.$emit('cateidfuc',this.filechecked[0].filecategoryid);
    },
    yulan(){
  this.$emit('yulan',this.filechecked[0]);
    },
    download(){
        // console.log("下载",this.filechecked)
        this.$emit('downloadurl',this.filechecked)
    },
    uploadfile() {
      this.filecate=  this.filelist.filter(item=>{
            if(item.checked===true){
                return item.filecategoryid;
            }
        })
        if(this.filecate[0]&& this.filecate[0].filecategoryid){
            this.$emit('filelist', this.filecate[0].filecategoryid);
        }
      this.$refs.uploadfile.click();
    },
    deletefile(){
     
      this.$emit('fileid',this.filechecked);
    },
    uploadfiles() {
      this.$refs.uploadfiles.click();
    },
    uploaddir() {
      this.$refs.uploaddir.click();
    },
    reload(){
       this.$emit('reload',new Date().getTime())
    },
    handleCtrlAClick(){
     this.filechecked.map(it=>{
       it.checked=true;
     })
    },
    handleShiftClick(item,index){
      const _this = this;
      _this.pre = _this.pre;
      let start = [index,_this.pre].sort((a,b)=>a-b);
      this.filelist.forEach((ele,index)=>{
            if(index<start[0]||index>start[1]){
        ele.checked=false;
         _this.$set(_this.filelist, index, ele);
        }else{
             ele.checked=true;
         _this.$set(_this.filelist, index, ele);
        }
    });
    },
    handleCtrlClick(item, index){
      this.contextmenuClose();
      if (index.type == "file") {
        this.$emit("fileClick", index);
      } else {
        this.$emit("DirClick", index);
      }
      this.pre = index
      item.checked = !item.checked;
      this.$set(this.filelist, index, item);
    },
    handleClick(item, index) {
      this.contextmenuClose();
      if (index.type == "file") {
        this.$emit("fileClick", index);
      } else {
        this.$emit("DirClick", index);
      }
      this.filelist.map(ele=>{
        if(item===ele){
          ele.checked=!ele.checked
        }else{
        ele.checked=false; 
        }
        return ele
      })
      this.$set(this.filelist, index, item);
      this.pre=index
    },
    handelDbclick(item, index) {
      this.contextmenuClose();
      if (item.type == "file") {
        this.$emit("fileDbClick", item);
      } else {
        this.$emit("DirDbClick", item);
      }
    },
    clealChecked() {
      const _this = this;
      this.filelist.forEach((ele, index) => {
        ele.checked = false;
        _this.$set(_this.filelist, index, ele);
      });
    },

    opencontextmenu($event) {
      $event.preventDefault();
      $event.stopPropagation();
      $event.stopImmediatePropagation();
      this.contextmenuClose();
    },
    bodycontextmenu($event) {
      this.opencontextmenu($event);
      this.clealChecked();
      this.showcontextmenufolder = true;
      this.styls2 = `left:${$event.layerX}px;top:${$event.layerY}px`;
      this.$emit("bodycontentmenu");
    },

    Handlecontextmenu($event, item, index) {
      this.$emit("filemenu");
      this.opencontextmenu($event);
      // console.log($event)
      this.showcontextmenu = true;
      if (this.filechecked.length === 1) {
        this.clealChecked();
      }
      item.checked = true;
       this.$set(this.filelist, index, item);
      this.$nextTick(()=>{
      let offsetLeft = $event.x - this.$refs.filebody.getBoundingClientRect().left;
      let offsetTop = $event.y - this.$refs.filebody.getBoundingClientRect().top;
      this.styls = `left:${offsetLeft}px;top:${offsetTop}px`;
      })

      // console.log('0000',this.styls)
    },
    
    Handlecontextmenu1($event, item, index) {
      console.log($event)
      this.$emit("filemenu");
      this.opencontextmenu($event);
      // console.log($event)
      this.showcontextmenu = true;
      if (this.filechecked.length === 1) {
        this.clealChecked();
      }
      item.checked = true;
      this.$set(this.filelist, index, item);
      this.styls = `left:${$event.layerX}px;top:${$event.layerY}px`;
      // console.log('0000',this.styls)
    },
    contextmenuClose() {
      this.showcontextmenu = false;
      this.showcontextmenufolder = false;
    },
    myfun(event){
      const _this = this;
   if(event.key=="a"&&event.ctrlKey==true){
        _this.selectAll();
      }
      if(event.keyCode==46){
         if(_this.filechecked.length!==0){
           _this.$emit('fileid',_this.filechecked);
         }
          
      }
    },
     clearEventBubble(evt) { 

  if (evt.stopPropagation) 

    evt.stopPropagation(); 

  else 

    evt.cancelBubble = true; 

  if (evt.preventDefault) 

    evt.preventDefault(); 

  else 

    evt.returnValue = false; 

} ,
handlemousedown(event){
      const _this = this;
       this.$emit("bodyclick");
      this.contextmenuClose();
      this.clealChecked();
       this.pre = 0;  
         _this.selList = []; 

    var fileNodes = document.getElementsByTagName("div"); 

    for ( var i = 0; i < fileNodes.length; i++) { 

      if (fileNodes[i].className.indexOf("paper") != -1) { 

        fileNodes[i].className = "paper"; 

        _this.selList.push(fileNodes[i]); 

      } 

    } 

    var isSelect = true; 
    _this.$nextTick(()=>{
      _this.showseldiv=true;
      var evt = event || arguments[0]; 
         _this.startX = (  evt.layerX||evt.x); 
    let selDiv = _this.$refs.selDiv;
    _this.startY = ( evt.layerY||evt.y); 
        selDiv.style.left = _this.startX + "px"; 

    selDiv.style.top = _this.startY + "px"; 

     _this._x = null; 

     _this._y = null; 
      _this.clearEventBubble(evt); 
    })
      

    },
    handlemove(event){
      const _this = this;
           let  evt = event || arguments[0]; 
           _this.$nextTick(()=>{
 let selDiv = _this.$refs.selDiv
      if (_this.showseldiv) { 

        if (selDiv.style.display == "none") { 

          selDiv.style.display = ""; 

        } 

        _this._x = ( evt.layerX||evt.x ); 

        _this._y = (evt.layerY||evt.y); 

        selDiv.style.left = Math.min(_this._x, _this.startX) + "px"; 

        selDiv.style.top = Math.min(_this._y, _this.startY) + "px"; 

        selDiv.style.width = Math.abs(_this._x - _this.startX) + "px"; 

        selDiv.style.height = Math.abs(_this._y - _this.startY) + "px"; 

        // ---------------- 关键算法 ---------------------  

        var _l = selDiv.offsetLeft, _t = selDiv.offsetTop; 

        var _w = selDiv.offsetWidth, _h = selDiv.offsetHeight; 

        for ( var i = 0; i < _this.selList.length; i++) { 

          var sl = _this.selList[i].offsetWidth + _this.selList[i].offsetLeft; 

          var st = _this.selList[i].offsetHeight + _this.selList[i].offsetTop; 

          if (sl > _l && st > _t && _this.selList[i].offsetLeft < _l + _w && _this.selList[i].offsetTop < _t + _h) { 
            if (_this.selList[i].className.indexOf("file-checked") == -1) { 
                 _this.filelist[i].checked=true;
              _this.$set(_this.filelist, i, _this.filelist[i]);
            } 
          } else { 
            if (_this.selList[i].className.indexOf("file-checked") != -1) { 
                 _this.filelist[i].checked=false;
              _this.$set(_this.filelist, i, _this.filelist[i]);

            } 

          } 

        } 

      } 

      _this.clearEventBubble(evt); 
           })
       
    },
    handleup(event){
      const _this = this;
      _this.showseldiv = false; 
      let selDiv = _this.$refs.selDiv
      _this._x=null;
      _this._y=null;
      _this.startX=null;
      _this.startY=null;
      // _this.selList=[];
        selDiv.style.left =0

        selDiv.style.top =0

        selDiv.style.width = 0

        selDiv.style.height =0;
    }
  },
  mounted(){
    const _this = this;
    window.addEventListener("keydown",_this.myfun);  
  },
  beforeDestroy(){
    const _this = this;
    window.removeEventListener("keydown",_this.myfun)
  }
  
};
</script>
